#include "ndlogin.h"

const QString NDLogin::HOST = "fsntserv.foodserv.nd.edu";
const QString NDLogin::LOGIN_PAGE = "/viewbal/index.cfm";
const QString NDLogin::TRANSACTIONS_PAGE = "/viewbal/points.cfm";

NDLogin::NDLogin(const QString& netID, QObject* parent)
	: QObject(parent)
{
	m_netID = netID;

	m_http = new QHttp(this);
	// Gotta use a secure connection!
	m_http->setHost(HOST, QHttp::ConnectionModeHttps);

	connect(m_http, SIGNAL(requestFinished(int,bool)), this, SLOT(slot_requestFinished(int,bool)));
}

void NDLogin::login(const QString& password)
{
	QHttpRequestHeader header("POST", LOGIN_PAGE);
	header.setValue("Host", HOST);
	header.setContentType("application/x-www-form-urlencoded");

	QByteArray encodedUsername = QUrl::toPercentEncoding(m_netID);
	QByteArray encodedPassword = QUrl::toPercentEncoding(password);

	QString loginString = "j_username=" + encodedUsername + "&j_password=" + encodedPassword;

	m_loginRequestId = m_http->request(header, loginString.toUtf8());
}

void NDLogin::slot_requestFinished(int id, bool error)
{
	if (error)
	{
		emit httpError(tr("HTTP error: %1.").arg(m_http->errorString()));
	}
	else if (id == m_loginRequestId)
	{
		QString results = m_http->readAll();

		QRegExp re_user("<span class=\"username\">(.*)</span>", Qt::CaseSensitive, QRegExp::RegExp2);
		re_user.setMinimal(true);

		// We were able to parse out the user's name, so we must be logged in
		if(re_user.indexIn(results) != -1)
		{
			QStringList cookies = m_http->lastResponse().allValues("Set-Cookie");

			QString cookieString;
			foreach (QString val, cookies)
			{
				cookieString.append(val.split(";")[0]).append("; ");
			}

			m_cookies = cookieString;

			emit loginSuccess(re_user.cap(1).replace("&nbsp;", " "));
		}
		// Bad netid/password or the account doesn't have food data
		else
		{
			emit loginFailure();
		}
	}
	else if (id == m_transactionsRequestId)
	{
		QString results = m_http->readAll();

		QString td_pattern = "<td(?:[^>]*)?>([^<]*)</td>";
		QRegExp re_transaction("<tr>\\s*" + td_pattern + "\\s*" + td_pattern + "\\s*" + td_pattern + "\\s*" + td_pattern + "\\s*" + td_pattern + "\\s*" + td_pattern + "\\s*</tr>", Qt::CaseSensitive, QRegExp::RegExp2);
		re_transaction.setMinimal(true);

		m_transactions.clear();

		int pos = 0;
		while ((pos = re_transaction.indexIn(results, pos)) != -1)
		{
			QStringList details;
			for (int i = 1; i <= 6; i++)
			{
				details << re_transaction.cap(i).replace("&nbsp;", " ");
			}
			m_transactions.append(details);
			pos += re_transaction.matchedLength();
		}

		emit gotTransactions(m_transactions);
	}
	else if (id == m_balancesRequestId)
	{
		QString results = m_http->readAll();
		QList<double>* balances = new QList<double>();

		QRegExp re_balances(tr("<td align=\"right\">(.*)</td>"), Qt::CaseInsensitive, QRegExp::RegExp2);
		re_balances.setMinimal(true);

		int pos = 0;
		while ((pos = re_balances.indexIn(results, pos)) != -1)
		{
			balances->append(re_balances.cap(1).replace('$', "").toDouble());
			pos += re_balances.matchedLength();
		}

		double domer = balances->at(1);
		double flex = balances->at(2) + balances->at(3);
		emit gotBalances(domer, flex);
	}
}

void NDLogin::getTransactions()
{
	QHttpRequestHeader header("GET", TRANSACTIONS_PAGE);
	header.setValue("Host", HOST);
	header.setValue("Cookie", m_cookies);

	m_transactionsRequestId = m_http->request(header);

	header.setRequest("GET", LOGIN_PAGE);
	m_balancesRequestId = m_http->request(header);
}

const QString& NDLogin::netID() const
{
	return m_netID;
}
